#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "Protocol.hpp"

static void Service(std::string ip, int port, int sock)
{
  while (1){
    request rt(0, 0, 0); 
    ssize_t size = recv(sock, &rt, sizeof(rt), 0);// 阻塞方式读取 
    if (size > 0){
      // 正常读取size字节的数据
      
      std::cout << "[" << ip << "]:[" << port  << "]# "<< rt._num1 << rt._op << rt._num2 << "=?"<< std::endl;
      response rp(0, 0);
      switch(rt._op)
      {
        case '+':
          rp._result = rt._num1 + rt._num2; 
      //    std::cout << "result:" << rp._result << std::endl;
          break;
        case '-':
          rp._result = rt._num1 - rt._num2; 
          break;
        case '*':
          rp._result = rt._num1 * rt._num2; 
          break;
        case '/':
          if (rt._num2 == 0){
            rp._code = 1;
          }
          else{
            rp._result = rt._num1 / rt._num2; 
          }
          break;
        default:
          rp._code = 2;
          break;
      }
      send(sock, &rp, sizeof(rp), 0);
    }
    else if (size == 0){
      // 对端关闭
      std::cout << "[" << ip << "]:[" << port  << "]# close" << std::endl;
      break;
    }
    else{
      // 出错
      std::cerr << sock << "read error" << std::endl; 
      break;
    }
  }

  close(sock);
  std::cout << "service done" << std::endl;
}

struct Task
{
  int _port;
  std::string _ip;
  int _sock;

  Task(int port, std::string ip, int sock)
    :_port(port)
    ,_ip(ip)
     ,_sock(sock)
  {}
  void Run()
  {
      Service(_ip, _port, _sock);
  }
};
